<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input
        v-model="pageParam.superSearchKeyWord"
        style="width: 200px;"
        placeholder="姓名和账号查询..."
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @input="handleFilter"
      />
      <!-- <el-select style="width: 140;" v-model="pageParam.orderParams" class="filter-item" placeholder="创建时间">
        <el-option v-for="item in createTimeOrderOptions" :key="item.key" :label="item.label" :value="item.value" />
      </el-select> -->
      <el-select v-model="pageParam.model.depName" placeholder="请选择科室" @change="getListByPage()">
        <el-option label="全部" value=""/>
        <el-option v-for="item in depList" :key="item.id" :label="item.depName" :value="item.depName"/>
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <el-table-column prop="depName" label="科室名" width="100px"/>
      <el-table-column prop="userName" label="值班人员姓名"/>
      <el-table-column prop="account" label="值班人员账号"/>
      <el-table-column :formatter="dateFormat" sortable="custom" prop="time" label="排班日期"/>
      <el-table-column sortable="custom" prop="createTime" label="创建时间"/>
      <el-table-column sortable="custom" prop="updateTime" label="修改时间"/>

      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button size="small" v-if="disable(row)" type="info" >时间已过</el-button>
          <el-button size="small" v-else type="warning" @click="handleUpdate(row)">修改</el-button>
          <el-button size="small" v-permission="['admin']"  type="danger" @click="deleteById(row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getListByPage"
    />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px"
               style="width: 400px; margin-left:50px;">

        <el-form-item label="排班日期" prop="time">
          <el-date-picker v-model="temp.time" type="date"
                          placeholder="选择日期"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :picker-options="pickerOptions"/>
        </el-form-item>
        <el-form-item label="科室" prop="depId">
          <el-select v-model="depId" placeholder="请选择科室" @change="getUserByDep()">
            <el-option v-for="item in depList" :key="item.id" :label="item.depName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-select v-model="temp.userId" placeholder="请选择值班人员" @change="showAccount">
            <el-option v-for="item in userList" :key="item.id" :label="item.realName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="账号">
          <span v-text="account"></span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入user的api
import {
  getAll,
  add,
  update,
  deleteById
} from '@/api/schedule'
import {
  getAllFather,
  getUserByDepId
} from '@/api/department'

// 导入组件  记得声明组件
import Pagination from '@/components/Pagination'

export default {
  components: { // 在这里声明组件
    Pagination
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          //如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      account:'',
      list: [], // 列表数据
      total: 0,
      listQuery: { // 分页 排序  查询参数
        pageNum: 1,
        pageSize: 5
      },
      fieldQuery: { // 按字段查询
        realName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      temp1: {
        id: undefined,
        userId: '',
        depName: '',
        time: ''
      },
      temp: {
        id: undefined,
        userId: '',
        depName: '',
        time: ''
      },
      rules: {
        time: [{
          required: true,
          message: '时间不能为空',
          trigger: 'blur'
        }]
      },
      pageParam: {
        pageNum: 1,
        pageSize: 5,
        model: {},
        orderParams: [],
        superSearchKeyWord: ''
      },
      depList: [],
      depId: '',
      userList: []
    }
  },
  created() {
    this.getListByPage()
    this.getAllDep()
  },
  methods: {
    deleteById(id){
      deleteById(id).then(()=>{
        this.$notify({
          title: '成功',
          message: '编辑成功',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    showAccount(){
      console.log(this.userList)
      console.log(this.temp.userId)
      for (let i of this.userList) {
        if (this.temp.userId === i.id) {
          this.account=i.account;
          return ;
        }
      }
      return this.account=''
    },
    dateFormat(row) {
      return row.time.substring(0, 10)
    },
    disable(row) {

      return new Date(row.time) < new Date()
    },
    getUserByDep() {
      this.temp.userId=''
      this.account=''
      getUserByDepId(this.depId)
        .then(res => {
          this.userList = res.content
        })
    },
    setDepName() {
      for (const i of this.depList) {
        if (this.depId == i.id) {
          this.temp.depName = i.depName
          break
        }
      }
    },
    setDepId(row) {
      for (const i of this.depList) {
        if (row.depName == i.depName) {
          this.depId = i.id
          this.temp.userId = row.userName
          break
        }
      }
    },
    getAllDep() {
      getAllFather().then(res => {
        this.depList = res.content
      })
    },
    sortChange(val) {
      // console.log("排序参数",val)
      const prop = val.prop
      const order = val.order === 'ascending' ? 'asc' : 'desc'
      let orderParam
      if (prop == 'createTime') {
        orderParam = 'creat_time' + ' ' + order
      } else if (prop == 'updateTime') {
        orderParam = 'update_time' + ' ' + order
      } else {
        orderParam = prop + ' ' + order
      }
      this.pageParam.orderParams = []
      this.pageParam.orderParams.push(orderParam)
      console.log(this.pageParam.orderParams)
      this.getListByPage()
    },
    getListByPage() {
      this.pageParam.pageNum = this.listQuery.pageNum
      this.pageParam.pageSize = this.listQuery.pageSize

      console.log(this.pageParam.orderParams)

      getAll(this.pageParam).then(res => {
        // console.log(res)
        this.list = res.content.list
        this.total = res.content.total
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getListByPage()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.setDepId(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.setDepName()
          add(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.setDepName()
          update(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    resetTemp() {
      this.temp = this.temp1
      this.depId = ''
    }
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
